package 力扣;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xiaok
 * @create 2020--11-23 16:16
 */

public class _146LRU缓存机制 {

    int capacity;
    LinkedHashMap<Integer, Integer> cache;

    // 使用 LinkedHashMap 实现 LRU算法
    public _146LRU缓存机制(int capacity) {
        this.capacity = capacity;
        cache = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return cache.size() > capacity;
            }
        };
    }

    public int get(int key) {
        return cache.getOrDefault(key, -1);
    }

    public void put(int key, int value) {
        cache.put(key, value);
    }
}
